package com.huluobo.a2206monthdemo.login;

import android.content.Intent;
import android.util.Log;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2206monthdemo.MainActivity;
import com.huluobo.a2206monthdemo.R;
import com.huluobo.a2206monthdemo.databinding.ActivityLoginBinding;
import com.huluobo.base.bean.Money;
import com.huluobo.base.db.AppDBUtils;
import com.huluobo.base.mvvm.BaseMVVMActivity;
import com.huluobo.base.net.Const;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

/**
 * Created by LC on 2024/8/31.
 */
public class LoginActivity extends BaseMVVMActivity<ActivityLoginBinding, LoginViewModel> {
    @Override
    protected void initData() {
        viewModel.loginSuccess.observe(this, userBeanResult -> {
            if (userBeanResult.getCode() == 200) {
                ToastUtils.showLong("欢迎回来:" + userBeanResult.getData().getUsername());
                SPUtils.getInstance().put(Const.PARAM_TOKEN, userBeanResult.getData().getToken());
                SPUtils.getInstance().put(Const.PARAM_USERNAME, userBeanResult.getData().getUsername());
                AppDBUtils.getInstance().getUserDao().insertUserInfo(userBeanResult.getData());
                Money money = new Money(10000f, userBeanResult.getData().getUsername());
                AppDBUtils.getInstance().getMoneyDao().insertUserMoney(money);
                EMClient.getInstance().login(userBeanResult.getData().getUsername(),
                        userBeanResult.getData().getPassword(), new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            }

                            @Override
                            public void onError(int code, String error) {
                                ToastUtils.showLong("登录环信失败:" + error + ",code:" + code);
                            }
                        });
            }
        });

        viewModel.loginFailed.observe(this, s -> {
            Log.i("TagA", "登录失败:" + s);
        });
    }

    @Override
    protected void initView() {
        binding.loginBtn.setOnClickListener(v -> {
            String username = binding.loginUsernameEt.getText().toString();
            String password = binding.loginPassword.getText().toString();
            if (!username.isEmpty() && !password.isEmpty()) {
                viewModel.login(username, password);
            } else {
                ToastUtils.showLong("用户名密码不能为空");
            }
        });
    }

    @Override
    protected Class<LoginViewModel> getViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }
}
